package com.interfaces.pay;

import com.alipay.api.*;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.interfaces.config.ProjectConfig;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 阿里支付宝支付相关
 */
public class AliPay {
    public static String outTradeNoGen(){
        /****************订单号生成*******************/
        Long times=new Date().getTime();
        LocalDateTime now = LocalDateTime.now();
        // 创建一个DateTimeFormatter实例，指定日期和时间的格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMddHHmmss");
        // 使用formatter格式化当前日期和时间
        String formattedDateTime = now.format(formatter);
        StringBuffer outTradeNoStr=new StringBuffer("ZFB");
        outTradeNoStr.append(formattedDateTime);
        String timesStr=times.toString();
        String timesStr6=timesStr.substring(timesStr.length()-6,timesStr.length());
        outTradeNoStr.append(timesStr6);
        String outTradeNo=outTradeNoStr.toString();
        /***********************************/
        return outTradeNo;
    }
    /**
     * 转账到个人
     * @return
     */
    public static String transfer(){
        String appId = "your_app_id";
        String privateKey = "your_private_key";
        String alipayPublicKey = "alipay_public_key";
        String serverUrl = "https://openapi.alipay.com/gateway.do";
        String charset = "UTF-8";
        String signType = "RSA2";

        String bizContent = "{" +
                "\"out_trade_no\":\"202501210001\"," +
                "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\"," +
                "\"biz_scene\":\"DIRECT_TRANSFER\"," +
                "\"payee_info\":{" +
                "\"identity\":\"recipient_alipay_account\"," +
                "\"identity_type\":\"ALIPAY_LOGON_ID\"," +
                "\"name\":\"recipient_name\"" +
                "}," +
                "\"trans_amount\":\"100.00\"," +
                "\"remark\":\"test transfer\"" +
                "}";

        String requestData = "app_id=" + appId +
                "&charset=" + charset +
                "&method=alipay.fund.trans.uni.transfer" +
                "&sign_type=" + signType +
                "&timestamp=" + System.currentTimeMillis() / 1000 +
                "&version=1.0" +
                "&biz_content=" + bizContent;

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(serverUrl);
            StringEntity entity = new StringEntity(requestData, charset);
            httpPost.setEntity(entity);
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

            // 这里需要根据你的私钥对请求进行签名，示例中暂时省略签名逻辑
            // String sign = signRequest(requestData, privateKey, signType);
            // httpPost.addHeader("sign", sign);

            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity!= null) {
                    String result = EntityUtils.toString(responseEntity, charset);
                    System.out.println(result);
                }
            } finally {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }


    public static String check(HttpServletRequest request) throws AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext ();) {
            String name =  ( String )iter.next();
            String[] values = (String[])requestParams.get(name);
            String valueStr="";
            for(int i = 0;i < values.length; i++){
                valueStr = (i== values.length-1)?valueStr+values[i]:valueStr+values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name,valueStr);
        }
        //切记alipayPublicCertPath是支付宝公钥证书路径，请去open.alipay.com对应应用下载。
        //boolean AlipaySignature.rsaCertCheckV1(Map<String, String> params, String publicKeyCertPath, String charset,String signType)
        boolean flag = AlipaySignature.rsaCertCheckV1(params,ProjectConfig.AliPayInit.merchantCertPath,"UTF-8","RSA2");
        return "";
    }
    /**
     * app支付
     * @param title 标题
     * @param outTradeNo 订单号
     * @param totalAmount 总价钱
     * @return
     */
    public static String appApy(String title,String outTradeNo,String totalAmount){
       //构造client
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置网关地址
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
        //设置应用Id
        certAlipayRequest.setAppId(ProjectConfig.AliPayInit.appId);
        //设置应用私钥
        certAlipayRequest.setPrivateKey(ProjectConfig.AliPayInit.merchantPrivateKey);
        //设置请求格式，固定值json
        certAlipayRequest.setFormat("json");
        //设置字符集
        certAlipayRequest.setCharset("UTF-8");
        //设置签名类型
        certAlipayRequest.setSignType(ProjectConfig.AliPayInit.signType);
        //设置应用公钥证书路径
        certAlipayRequest.setCertPath(ProjectConfig.AliPayInit.merchantCertPath);
        //设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(ProjectConfig.AliPayInit.alipayCertPath);
        //设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(ProjectConfig.AliPayInit.alipayRootCertPath);

        try  {
            //构造client
            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest ();
            //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel ();
            model.setSubject (title);
            model.setOutTradeNo (outTradeNo);
            model.setTotalAmount (totalAmount);
            request.setBizModel (model);
            request.setNotifyUrl (ProjectConfig.AliPayInit.notifyUrl);
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            System.err.println(response.getMsg());
            System.err.println(response.getCode());
            return response.getBody();
        }  catch (AlipayApiException e ) {
            e.printStackTrace();
            return "";
        }
    }
}

